import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import layout from '@/views/layout'
import home from '@/views/home'
import ask from '@/views/ask'
import video from '@/views/video'
import mine from '@/views/mine'
import UserEdit from '@/views/mine/UserEdit'
import article from '@/views/article'
import search from '@/views/search'
import SearchResult from '@/views/search/SearchResult'
import chat from '@/views/mine/RobotChat'
import store from '@/store'
import { Toast } from 'vant'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home' },
  { name: 'login', path: '/login', component: login },
  { name: 'search', path: '/search', component: search },
  { name: 'article', path: '/article/:id', component: article },
  { name: 'chat', path: '/chat', component: chat },
  { name: 'SearchResult', path: '/search/result', component: SearchResult },
  {
    name: 'UserEdit',
    path: '/mine/edit',
    component: UserEdit,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      { name: 'home', path: '/home', component: home },
      { name: 'ask', path: '/ask', component: ask },
      { name: 'video', path: '/video', component: video },
      {
        name: 'mine',
        path: '/mine',
        component: mine,
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

/*
  to：去哪，   得到的是路由信息对象
  from：从哪来 得到的是路由信息对象
  next：是一个函数，函数的功能是放行，调用它代表放行，不调用不放行
        放行函数跟$router.push用法一样
        例如：$router.push('/login')，next也能 next('/login'),这个时候可以说是放行到login
        也就是跳转到login
*/
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    // 有需要登录的标记
    if (store.state.user.tokenObj.token) {
      // 代表登录了，直接放行
      next()
    } else {
      // 提示
      Toast('请先登录')
      // 放行到登录页
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else {
    // 直接放行
    next()
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
